package com.piece.core.framework.util.security.coder;

import com.piece.core.framework.util.string.StringUtil;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

public class AESCoder {

    /**
     * 密钥算法
     */
    private static final String ENCRPTY_KEY = "AES";

    private static final String KEY_ALGORITHM = "8NONwyJtHesysWpM";

    /**
     * 加密/解密算法 / 工作模式 / 填充方式
     */
    private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

    /**
     * AES加密
     */
    public static byte[] aesEncryptToBytes(String content) throws Exception {
        return aesEncryptToBytes(content, KEY_ALGORITHM);
    }

    /**
     * AES加密
     */
    public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ENCRPTY_KEY);
        keyGenerator.init(128);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), ENCRPTY_KEY));
        return cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * AES加密为base64 code
     */
    public static String aesEncrypt(String content) throws Exception {
        return aesEncrypt(content, KEY_ALGORITHM);
    }

    /**
     * AES加密为base64 code
     */
    public static String aesEncrypt(String content, String encryptKey) throws Exception {
        return new BASE64Encoder().encode(aesEncryptToBytes(content, encryptKey)).replaceAll(System.getProperty("line.separator"), "");
    }

    /**
     * AES解密
     */
    public static String aesDecryptByBytes(byte[] encryptBytes) throws Exception {
        return aesDecryptByBytes(encryptBytes, KEY_ALGORITHM);
    }

    /**
     * AES解密
     */
    public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ENCRPTY_KEY);
        keyGenerator.init(128);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        SecretKeySpec secretKeySpec = new SecretKeySpec(decryptKey.getBytes(StandardCharsets.UTF_8), ENCRPTY_KEY);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes, StandardCharsets.UTF_8);
    }

    /**
     * 将base64 code AES解密
     */
    public static String aesDecrypt(String encryptStr) throws Exception {
        return aesDecrypt(encryptStr, KEY_ALGORITHM);
    }

    /**
     * 将base64 code AES解密
     */
    public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {
        return StringUtil.isEmpty(encryptStr) ? null : aesDecryptByBytes(new BASE64Decoder().decodeBuffer(encryptStr), decryptKey);
    }
}
